﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Code.Models;
using QianBuo.Lottery.Web.Models;

namespace QianBuo.Lottery.Web.Areas.Manage.Controllers
{
    [HandleError]
    public class BaseController:Controller
    {
        public Guid AdminID { get; set; }
        public AdminModel Admin { get; set; }
        public HashTable<Guid, UserModel> OnLineUsers { get; private set; }
        public HashTable<Guid, AdminModel> OnLineManagers { get; private set; }

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!User.Identity.IsAuthenticated || !User.IsInRole("Manager"))
            {
                filterContext.Result = RedirectToAction("Index", "Login", new { ReturnUrl = Request.RawUrl });
                return;
            }

            var auths = (filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true) as AuthorizeAttribute[])
                .Concat(filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true) as AuthorizeAttribute[]);

            foreach (var item in auths)
            {
                item.OnAuthorization(filterContext);
                if (filterContext.Result is HttpUnauthorizedResult)
                {
                    string str = "<h2>您的权限不足！</h2><a href='javascript:history.go(-1)'>返回</a></p>";
                    str += string.Format("<p>5秒之后将跳转到<a href='{0}'>首页</a></p><script>setTimeout(function(){{location.href='{0}'}},5000);</script>", Url.Action("Index", "Home"));
                    filterContext.Result = Content(str);
                    return;
                }
            }

            OnLineUsers = Global.OnLineUsers;
            OnLineManagers = Global.OnLineManagers;           

            var data = User.Identity.Name.Split('&').ToDictionary(p => p.Split(':')[0], p => p.Split(':')[1]);
            AdminID = (Guid)(Session["AdminID"] ?? new Guid(data["ManageLoginID"]));
            Session["AdminID"] = AdminID;
            Admin = OnLineManagers[AdminID];

            if (Admin != null && Admin.SessionID != Session.SessionID)
            {
                string str = string.Format("<script>alert('您的账号已在:{1}登录\\r\\n请尽快修改密码！');location.href='{0}';</script>", Url.Action("Index", "Login", new { ReturnUrl = Request.RawUrl }), Admin.LoginIP);
                filterContext.Result = Content(str);
                FormsAuthentication.SignOut();
                return;
            }

            if (Admin == null || Admin.IsLoad || Admin.AddTime.AddSeconds(5) < DateTime.Now)
            {
                var AM = new Code.BLL.AdminManage();
                var a = AM.Select(s => s.FirstOrDefault(p => p.ID == AdminID));
                if (a == null)
                {
                    filterContext.Result = RedirectToAction("Index", "Login", new { ReturnUrl = Request.RawUrl });
                    return;
                }
                Admin = new AdminModel
                {
                    AdminID = AdminID,
                    LoginName = data["LoginName"],
                    RoleID = a.RoleID,
                    State = (AdminState)a.State,
                    AddTime = DateTime.Now,
                    SessionID=Session.SessionID,
                    LoginIP=Request.UserHostAddress,
                };
            }

            if (Admin.State == AdminState.Locked)
            {
                string str = string.Format("<script>alert('该的账号已被锁定\\r\\n请联系上级解锁！');location.href='{0}';</script>", Url.Action("Index", "Login", new { ReturnUrl = Request.RawUrl }));
                filterContext.Result = Content(str);
                FormsAuthentication.SignOut();
                return;
            }

            SetAuthTicket(Admin);
            OnLineManagers[AdminID] = Admin;

            var _us = OnLineUsers.Where(p => p.Value.SessionID == Session.SessionID).Select(p=>p.Key).ToArray();
            //var _as = OnLineManagers.Where(p => p.Value.SessionID == Session.SessionID && p.Value.AdminID != AdminID).Select(p => p.Key).ToArray();

            foreach (var item in _us)
                OnLineUsers.Remove(item);
            //foreach (var item in _as)
            //    OnLineManagers.Remove(item);
        }

        protected void SetAuthTicket(AdminModel admin)
        {
            HttpCookie authtick = Request.Cookies[FormsAuthentication.FormsCookieName];
            FormsAuthenticationTicket tick = FormsAuthentication.Decrypt(authtick.Value);
            var aus = System.Configuration.ConfigurationManager.GetSection("system.web/authentication") as System.Web.Configuration.AuthenticationSection;

            if (aus != null)
            {
                var str = string.Format("ManageLoginID:{0}&LoginName:{1}&RoleID:{2}&Roles:Manager", admin.AdminID, admin.LoginName, admin.RoleID);

                tick = new FormsAuthenticationTicket(2, str, tick.IssueDate, DateTime.Now.AddMinutes(aus.Forms.Timeout.TotalMinutes), false, tick.UserData);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(tick));
                Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
                Response.Cookies.Add(cookie);
            }
        }

        protected override void OnException(ExceptionContext filterContext)
        {
            string msg = "系统错误";
            if (filterContext.Exception is AppException)
                msg = filterContext.Exception.Message;
            ViewData["Error_Msg"] = msg;
            filterContext.Result = View("Error");
        }

    }
}